package org.syx.edl.support;

import org.syx.edl.ItemValidator;
import org.syx.edl.validate.HibernateValidatorManager;

import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * @author:whh
 * @date: 2025-09-05 23:51
 * <p></p>
 */
public class DefaultItemValidator<T> implements ItemValidator<T> {


    private HibernateValidatorManager validator;
    @Override
    public void open() throws Exception {
        validator = HibernateValidatorManager.getInstance();
    }

    @Override
    public void validate(T item) throws ValidationException {

        Set<ConstraintViolation<T>> validate = validator.validate(item);

        if(!validate.isEmpty()){
            StringBuilder message=new StringBuilder();
            message.append("validate error for : item [")
                    .append(item).append("], constraint violations :").append(System.lineSeparator());

            int len=validate.size();
            for (ConstraintViolation<T> c : validate) {
                message.append("[ ").append(c.getPropertyPath()).append(" ").append(c.getMessage()).append(" ]");
                if(len!=1){
                   message.append(System.lineSeparator());
                }
                len--;
            }

            throw new ValidationException(message.toString());


        }


    }

    @Override
    public void close() throws Exception {
        validator.shutdown();
    }
}
